import moment from 'moment'
import { history } from 'umi'
import { message } from 'antd'
import { parse } from 'querystring';

// const ip = "https://yuncommunity.com:8003/"
const ip = "http://192.168.1.4:8003/"
const host = ip + "v1/client/"

/**
 * 发送网络请求
 * @param api 接口
 * @param params 参数
 * @param success 成功后回调
 * @param fail 失败后回调
 */
export async function request(api: string, params: any, success: (data: any, total: any) => void, fail: (data: any, code: any) => void) {
  let url = host + api + "?"
  if (!params) {
    params = {}
  }
  params.token = localStorage.token
  for (let key in params) {
    url += key + "=" + params[key] + "&"
  }
  url = encodeURI(url)
  return fetch(url)
    .then(resp => resp.json())
    .then(res => {
      if (res.code < 0) {
        if (res.code === -1) { // 登录已过期
          localStorage.token = ""
          history.replace("/login")
        } else { // 不需要处理的错误提示
          message.error(res.data)
        }
      } else if (res.code === 0) {
        if (success) {
          success(res.data, res.total)
        }
      } else {
        if (fail) {
          fail(res.data, res.code)
        }
      }
      return res
    })
    .catch(e => console.log(e))
}

/**
 * 格式化时间
 * @param time 时间字符串
 */
export function formatTime(time: string) {
  if (!time) {
    return ""
  }
  return time.replace("T", " ").substring(0, 16)
}

/**
 * 格式化时间
 * @param time 时间long类型
 */
export function formatTimeLong(time: string) {
  return moment(parseFloat(time)).format("YYYY-MM-DD HH:mm")
}

/**
 * 获取url参数
 * @param key url参数的key
 * @param defaultValue url参数的默认值
 */
export function getUrlParams(key: string, defaultValue: any) {
  let regexS = "[\\?&]" + key + "=([^&#]*)";
  let regex = new RegExp(regexS);
  let results = regex.exec(window.location.href);
  let value = defaultValue
  if (results) {
    value = results[1]
  }
  return value
}

export function getPageQuery() {
  return parse(window.location.href.split('?')[1])
};
